/*
* Copyright (c) 2011 learemraf@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.googlecode.frank.driver.impl;

import static com.google.common.base.Preconditions.checkArgument;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.lang.time.StopWatch;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.googlecode.frank.driver.FrankDriver;
import com.googlecode.frank.driver.Operation;
import com.googlecode.frank.driver.Request;
import com.googlecode.frank.driver.Response;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.CommonsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

/**
 * @author farmerl
 */
public class FrankDriverImpl implements FrankDriver {

    private static final Logger LOG = LoggerFactory.getLogger(FrankDriverImpl.class);

    public void touch(String query) {
        List<String> touch = franklyMap(query, "touch");
        System.out.println(touch.get(0));
        checkArgument(touch.isEmpty(), "Could not find anything matching %s", query);
    }

    public void flash(String query) {
        List<String> matches = franklyMap(query, "flash");
    }

    public boolean elementExists(String query) {
        List<String> matches = franklyMap(query, "accessibilityLabel");
        return !matches.isEmpty();
    }

    public boolean checkElementExist(String query) {
        return elementExists(query);
    }

    public boolean checkElementDoesNotExist(String query) {
        return elementExists(query);
    }

    public boolean viewWithMarkExists(String expectedMark) {
        return elementExists("view marked:'#{" + expectedMark + "}'");
    }

    public boolean checkViewWithMarkExists(String expectedMark) {
        return checkElementExist("view marked:'#{" + expectedMark + "}'");
    }

    public boolean elementExistsAndIsNotHidden(String query) {
        List<String> isHidden = franklyMap(query, "isHidden");
        for (String element : isHidden) {
            if (isHidden.equals("true")) {
                isHidden.remove(element);
            }
        }
        return !isHidden.isEmpty();
    }

    public List<String> applicationExecute(String methodName, String... args) {
        Operation operation = new Operation();
        operation.setMethod_name(methodName);
        operation.setArguments(Arrays.asList(args));

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Response response = postToUispecServer("", "app_exec", operation);
        stopWatch.stop();
        LOG.debug("MAP applying {} with args {} to Application delegate took {}",
                new Object[]{methodName, args, stopWatch.getTime()});
        if (!response.getOutcome().equalsIgnoreCase("SUCCESS")) {
            throw new RuntimeException(methodName + " failed because: "
                    + response.getReason() + " details " + response.getDetails());
        }
        return response.getResults();
    }

    public List<String> franklyMap(String query, String methodName, String... args) {
        Operation operation = new Operation();
        operation.setMethod_name(methodName);
        operation.setArguments(Arrays.asList(args));

        System.out.println("operaton***" + operation.toString());
        Response response = postToUispecServer(query, "/map", operation);

        if (!response.getOutcome().equalsIgnoreCase("SUCCESS")) {
            throw new RuntimeException(methodName + " : " + query + " failed because: "
                    + response.getReason() + " details " + response.getDetails());
        }
        return response.getResults();
    }

    public void franklyDump() {
        Response response = getToUispecServer("dump");
        //LOG.info(response.toString());
    }

    public boolean franklyOrientedPortrait() {
        return "portrait".equals(franklyCurrentOrientation());
    }

    public boolean franklyOrientedLandscape() {
        return "landscape".equals(franklyCurrentOrientation());
    }

    public String franklyCurrentOrientation() {
        Response response = getToUispecServer("orientation");
        LOG.debug("Response for franklyCurrentOrientation : {}", response.toString());
        //TODO : See whats coming back as frank cucumber code is looking for 'orientation'
        return response.getResults().get(0);
    }

    public boolean franklyIsAccessibilityEnabled() {
        Response response = getToUispecServer("accessibility_check");
        //TODO : See whats coming back as frank cucumber code is looking for 'accessibility_check'
        System.out.println(response.getResults().get(0));
        return response.getResults().get(0).equalsIgnoreCase("true");
    }

    public void waitForFrankToComeUp() {
        throw new NotImplementedException();
    }

    public boolean franklyPing() {
        try {
            getToUispecServer("");
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    private Response postToUISpecServer(String query, String verb, Operation operation) {
        Request request = new Request();
        request.setQuery(query);
        request.setOperation(operation);

        HttpClient httpClient = new HttpClient();
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(new CommonsClientHttpRequestFactory(httpClient));
        List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
        converters.add(new MappingJacksonHttpMessageConverter());
        restTemplate.setMessageConverters(converters);

        HttpEntity<Request> requestEntity = new HttpEntity<Request>(request);

        HttpEntity<Response> responseEntity = restTemplate.exchange(frankUrlFor(verb),
                HttpMethod.POST, requestEntity, Response.class);
        return responseEntity.getBody();
    }

    public Response postToUispecServer(String query, String verb, Operation operation) {
        // return postToUISpecServer(query, verb, operation);
        return postToUispecServerInternal(query, verb, operation);
    }

    private Response postToUispecServerInternal(String query, String verb, Operation operation) {
        Request request = new Request();

        request.setQuery(query);
        request.setOperation(operation);

        System.out.println("REQUEST = " + request.toString());

        Response response = null;
        HttpURLConnection urlc = null;
        try {
            //Create URL
            URL url = new URL(frankUrlFor(verb));
            URLConnection conn = null;
            try {
                conn = url.openConnection();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            //Create URL Conn

            urlc = (HttpURLConnection) conn;

            try {
                //Set Request method as Get
                urlc.setRequestMethod("POST");

            } catch (ProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


            try {


                ObjectMapper mapper = new ObjectMapper(); // from org.codeahaus.jackson.map

                urlc.setDoOutput(true);
                //urlc.connect();
                mapper.writeValue(urlc.getOutputStream(), request);
                System.out.println(urlc.toString());
                response = mapper.readValue(urlc.getInputStream(), Response.class);

                System.out.println("Response" + response.toString());

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            urlc.disconnect();
        }


        return response;
    }

    private Response getFromUISpecServer(String verb) {
        HttpClient httpClient = new HttpClient();
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(new CommonsClientHttpRequestFactory(httpClient));
        List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
        converters.add(new MappingJacksonHttpMessageConverter());
        restTemplate.setMessageConverters(converters);

        HttpEntity<Response> responseEntity = restTemplate.exchange(frankUrlFor(verb),
                HttpMethod.GET, null, Response.class);
        return responseEntity.getBody();
    }

    public Response getToUispecServer(String verb) {
        // return getFromUISpecServer(verb);
        return getFromUISpecServerInternal(verb);
    }

    private Response getFromUISpecServerInternal(String verb) {
        Response response = null;
        try {
            //Create URL
            URL url = new URL(frankUrlFor(verb));
            URLConnection conn = null;
            try {
                conn = url.openConnection();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            //Create URL Conn
            HttpURLConnection urlc = null;
            urlc = (HttpURLConnection) conn;

            try {
                //Set Request method as Get
                urlc.setRequestMethod("GET");

            } catch (ProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {

                urlc.connect();
                InputStream inputStream = urlc.getInputStream();
                char[] buf = new char[1024];
                int read = 0;
                Reader reader = new InputStreamReader(inputStream);

                StringBuffer jsonResponse = new StringBuffer();
                while ((read = reader.read(buf)) >= 0) {
                    jsonResponse.append(buf);
                }
                response = new Response();
                response.setOutcome("SUCCESS");
                response.setResults(Arrays.asList(jsonResponse.toString()));

                System.out.println("RESPONSE = " + response.toString());


            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return response;
    }

    public String frankUrlFor(String verb) {
        //Create URL string
        String url = "http://localhost:37265/" + verb;
        return url;
    }
}
